import re
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import tkinter as tk
from tkinter import filedialog

def parse_log(file_path):
    # 正则匹配时间戳和TimerTask startTime行
    time_pattern = re.compile(r'\[INFO\]\[(\d{2}:\d{2}:\d{2}\.\d{3})\]')
    start_time_pattern = re.compile(r'TimerTask startTime\(s\):([\d.e+-]+)')
    
    timestamps = []
    start_times = []
    
    with open(file_path, 'r') as f:
        for line in f:
            time_match = time_pattern.search(line)
            if not time_match:
                #print("not match:", line)
                continue
            timestamp_str = time_match.group(1)
            
            # 提取TimerTask startTime
            if "TimerTask startTime" in line:
                # 转换为datetime对象
                timestamp = datetime.strptime(timestamp_str, "%H:%M:%S.%f")
                timestamps.append(timestamp)
                
                # 提取数值时间戳（可选）
                start_time_match = start_time_pattern.search(line)
                if start_time_match:
                    start_time = float(start_time_match.group(1))
                    start_times.append(start_time)
            
    return timestamps, start_times

def plot_results(timestamps):
    if len(timestamps) < 2:
        print("Not enough data points to plot")
        return

    # 计算时间间隔（单位：毫秒）
    intervals = []
    prev_time = timestamps[0]
    for t in timestamps[1:]:
        delta = (t - prev_time).total_seconds() * 1000  # 转换为毫秒
        intervals.append(delta)
        prev_time = t

    # 创建绘图
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8))
    
    # 绘制时间点分布
    ax1.plot(timestamps, [1]*len(timestamps), 'o', markersize=5)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S.%f"))
    ax1.set_title("TimerTask startTime Distribution")
    ax1.set_yticks([])

    # 绘制时间间隔分布
    ax2.plot(range(len(intervals)), intervals, 'ro-', markersize=5)
    ax2.axhline(50, color='green', linestyle='--', label='Expected 50ms')
    ax2.set_title(f"Time Intervals (Avg: {sum(intervals)/len(intervals):.2f}ms)")
    ax2.set_xlabel("Sequence Number")
    ax2.set_ylabel("Interval (ms)")
    ax2.legend()
    
    plt.tight_layout()
    plt.savefig("timer_analysis.png")
    plt.show()

def select_log_file():
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口
    file_path = filedialog.askopenfilename(
        title="选择日志文件",
        filetypes=[("Log files", "*.log"), ("All files", "*.*")]
    )
    root.destroy()
    return file_path


if __name__ == "__main__":
    log_file = select_log_file()
    if not log_file:
        print("未选择文件，程序退出")
        exit()
    
    print("已选择日志文件:", log_file)
    timestamps, _ = parse_log(log_file)
    plot_results(timestamps)